<template>
    <div class="vaccine-statistics">
        <div class="page-header">
            <h1>疫苗统计</h1>
            <div class="update-time">
                统计时间: {{ statisticsTime }}
            </div>
        </div>

        <!-- 总体统计卡片 -->
        <el-row :gutter="20" class="summary-cards">
            <el-col :xs="12" :sm="6" :md="6" :lg="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="card-content">
                        <div class="card-icon total">
                            <el-icon>
                                <Box />
                            </el-icon>
                        </div>
                        <div class="card-info">
                            <div class="card-value">{{ totalVaccines }}</div>
                            <div class="card-label">疫苗种类</div>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <el-col :xs="12" :sm="6" :md="6" :lg="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="card-content">
                        <div class="card-icon normal">
                            <el-icon>
                                <CircleCheck />
                            </el-icon>
                        </div>
                        <div class="card-info">
                            <div class="card-value">{{ stockDistribution.normalStock }}</div>
                            <div class="card-label">库存正常</div>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <el-col :xs="12" :sm="6" :md="6" :lg="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="card-content">
                        <div class="card-icon low">
                            <el-icon>
                                <Warning />
                            </el-icon>
                        </div>
                        <div class="card-info">
                            <div class="card-value">{{ stockDistribution.lowStock }}</div>
                            <div class="card-label">库存不足</div>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <el-col :xs="12" :sm="6" :md="6" :lg="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="card-content">
                        <div class="card-icon high">
                            <el-icon>
                                <TrendCharts />
                            </el-icon>
                        </div>
                        <div class="card-info">
                            <div class="card-value">{{ stockDistribution.highStock }}</div>
                            <div class="card-label">高库存</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 规格统计 -->
        <el-row :gutter="20" class="chart-row">

            <!-- 库存异常疫苗卡片 -->
            <el-col :xs="24" :sm="24" :md="24" :lg="24" class="card-col" @mouseenter="onLowHover"
                @mouseleave="onLowLeave">
                <el-card shadow="hover" class="warning-card" v-if="lowStockVaccines.length > 0">
                    <template #header>
                        <div class="warning-header">
                            <div class="header-left">
                                <el-icon>
                                    <Warning />
                                </el-icon>
                                <span>低库存疫苗</span>
                                <el-tag type="danger" size="small">{{ lowStockVaccines.length }}个疫苗</el-tag>
                            </div>
                            <div class="card-actions" v-if="lowStockVaccines.length > pageSizes">
                                <el-button text size="small" @click="LowPrevPage" :disabled="currentLowStockPage === 0">
                                    <el-icon>
                                        <ArrowLeft />
                                    </el-icon>
                                </el-button>
                                <span class="page-info">
                                    {{ currentLowStockPage + 1 }}/{{ TotalPages }}
                                </span>
                                <el-button text size="small" @click="LowNextPage"
                                    :disabled="currentLowStockPage === TotalPages - 1">
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <div class="warning-content">
                        <div v-for="vaccine in currentLowStockData" :key="vaccine.id" class="warning-item">
                            <div class="vaccine-info">
                                <div class="vaccine-name">{{ vaccine.vaccineName }}</div>
                                <div class="vaccine-details">
                                    <span class="manufacturer">{{ vaccine.manufacturer }}</span>
                                    <el-tag size="small" type="info">{{ vaccine.specification }}</el-tag>
                                    <el-tag size="small">{{ vaccine.batchNumber }}</el-tag>
                                </div>
                                <div class="storage-info">
                                    <span class="storage-condition">{{ vaccine.storageCondition }}</span>
                                    <span class="validity-period">有效期：{{ vaccine.validityPeriod }}个月</span>
                                </div>
                            </div>
                            <div class="warning-actions">
                                <el-button type="primary" size="small" @click="goToVaccineDetail(vaccine.id)">
                                    查看详情
                                </el-button>

                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <!-- 高库存卡片 -->
            <el-col :xs="24" :sm="24" :md="24" :lg="24" class="card-col" @mouseenter="onHighHover"
                @mouseleave="onHighLeave">
                <el-card shadow="hover" class="warning-cards" v-if="highStockVaccines.length > 0">
                    <template #header>
                        <div class="warning-header">
                            <div class="header-left">
                                <el-icon>
                                    <Warning />
                                </el-icon>
                                <span>高库存疫苗</span>
                                <el-tag type="danger" size="small">{{ highStockVaccines.length }}个疫苗</el-tag>
                            </div>
                            <div class="card-actions" v-if="highStockVaccines.length > HighPageSize">
                                <el-button text size="small" @click="HighPrevPage"
                                    :disabled="currentHighStockPage === 0">
                                    <el-icon>
                                        <ArrowLeft />
                                    </el-icon>
                                </el-button>
                                <span class="page-info">
                                    {{ currentHighStockPage + 1 }}/{{ TotalPages }}
                                </span>
                                <el-button text size="small" @click="HighNextPage"
                                    :disabled="currentHighStockPage === HighPageSize - 1">
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <div class="warning-content">
                        <div v-for="vaccine in currentHighStockData" :key="vaccine.id" class="warning-item">
                            <div class="vaccine-info">
                                <div class="vaccine-name">{{ vaccine.vaccineName }}</div>
                                <div class="vaccine-details">
                                    <span class="manufacturer">{{ vaccine.manufacturer }}</span>
                                    <el-tag size="small" type="info">{{ vaccine.specification }}</el-tag>
                                    <el-tag size="small">{{ vaccine.batchNumber }}</el-tag>
                                </div>
                                <div class="storage-info">
                                    <span class="storage-condition">{{ vaccine.storageCondition }}</span>
                                    <span class="validity-period">有效期：{{ vaccine.validityPeriod }}个月</span>
                                </div>
                            </div>
                            <div class="warning-actions">
                                <el-button type="primary" size="small" @click="goToVaccineDetail(vaccine.id)">
                                    查看详情
                                </el-button>

                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <!-- 规格统计 -->
            <el-col :xs="24" :sm="12" :md="12" :lg="12" class="card-col">
                <el-card shadow="hover" class="chart-card" @mouseenter="onSpecHover" @mouseleave="onSpecLeave">
                    <template #header>
                        <div class="card-header">
                            <el-icon>
                                <PieChart />
                            </el-icon>
                            <span>规格分布</span>
                            <div class="card-actions" v-if="specTotalPages > 1">
                                <el-button text size="small" @click="prevSpecPage" :disabled="currentSpecPage === 0">
                                    <el-icon>
                                        <ArrowLeft />
                                    </el-icon>
                                </el-button>
                                <span class="page-info">
                                    {{ currentSpecPage + 1 }}/{{ specTotalPages }}
                                </span>
                                <el-button text size="small" @click="nextSpecPage"
                                    :disabled="currentSpecPage === specTotalPages - 1">
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <div class="chart-container">
                        <div v-if="specificationStats.length > 0" class="spec-list">
                            <div v-for="item in currentSpecData" :key="item.name" class="manufacturer-item">
                                <div class="manufacturer-name">{{ item.name }}</div>
                                <div class="manufacturer-value">{{ item.value }} 种</div>
                                <div class="manufacturer-percentage">
                                    {{ (item.value / totalVaccines * 100).toFixed(1) }}%
                                </div>
                                <el-progress :percentage="+(item.value / totalVaccines * 100).toFixed(1)"
                                    :show-text="false" class="manufacturer-progress" />
                            </div>

                        </div>
                        <div v-else class="empty-data">
                            <el-empty description="暂无规格数据" />
                        </div>
                    </div>
                </el-card>
            </el-col>

            <!-- 生产商统计 -->
            <el-col :xs="24" :sm="12" :md="12" :lg="12" @mouseenter="onManufacturerHover"
                @mouseleave="onManufacturerLeave" class="card-col">
                <el-card shadow="hover" class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <el-icon>
                                <OfficeBuilding />
                            </el-icon>
                            <span>生产商分布</span>
                            <div class="card-actions" v-if="totalPages > 1">
                                <el-button text size="small" @click="prevPage" :disabled="currentPage === 0">
                                    <el-icon>
                                        <ArrowLeft />
                                    </el-icon>
                                </el-button>
                                <span class="page-info">
                                    {{ currentPage + 1 }}/{{ totalPages }}
                                </span>
                                <el-button text size="small" @click="nextPage"
                                    :disabled="currentPage === totalPages - 1">
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <div class="chart-container">
                        <div v-if="manufacturerStats.length > 0" class="manufacturer-list">
                            <div v-for="item in currentPageData" :key="item.name" class="manufacturer-item">
                                <div class="manufacturer-name">{{ item.name }}</div>
                                <div class="manufacturer-value">{{ item.value }} 种</div>
                                <div class="manufacturer-percentage">
                                    {{ (item.value / totalVaccines * 100).toFixed(1) }}%
                                </div>
                                <el-progress :percentage="+(item.value / totalVaccines * 100).toFixed(1)"
                                    :show-text="false" class="manufacturer-progress" />
                            </div>


                        </div>
                        <div v-else class="empty-data">
                            <el-empty description="暂无生产商数据" />
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import axios from 'axios'
import { useRouter } from "vue-router";
const router = useRouter();
// 响应式数据
const statisticsTime = ref('')
const totalVaccines = ref(0)
const stockDistribution = ref({
    lowStock: 0,
    normalStock: 0,
    highStock: 0
})
const specificationStats = ref([])
const manufacturerStats = ref([])
const loading = ref(false)
const lowStockVaccines = ref([])
const highStockVaccines = ref([])


// 获取疫苗统计数据
const fetchVaccineStatistics = async () => {
    loading.value = true
    await axios.get('http://127.0.0.1:8081/vaccine/statistics/vaccine', {
        headers: {
            'X-Admin-Token': sessionStorage.getItem("token")
        },
    }).then((req) => {

        if (req.data.success === true) {
            ElNotification({
                message: req.data.message,
                type: "success",
                position: 'bottom-right',
            })
            statisticsTime.value = req.data.data.statisticsTime
            specificationStats.value = req.data.data.specificationStats
            manufacturerStats.value = req.data.data.manufacturerStats
            totalVaccines.value = req.data.data.totalVaccines
            stockDistribution.value = req.data.data.stockDistribution[0]
            lowStockVaccines.value = req.data.data.lowStockVaccines
            highStockVaccines.value = req.data.data.highStockVaccines
        } else {
            ElNotification({
                message: req.data.message,
                type: "info",
                position: 'bottom-right',
            })
        }

    }).catch((error) => {
        ElMessage.error('请求失败，请检查网络连接');
    }).finally(() => {
        loading.value = false
    })
}


// 规格分布响应式数据
const currentSpecPage = ref(0)
const specPageSize = 6 // 每页显示6条数据

// 生产商分布响应式数据
const currentPage = ref(0)
const pageSize = 6 // 每页显示6条数据
//低库存分布响应式数据
const currentLowStockPage = ref(0)
const pageSizes = 2 // 每页显示2条
//高库存响应式数据
const currentHighStockPage = ref(0)
const HighPageSize = 2 // 每页显示2条
// 计算属性
const specTotalPages = computed(() => {
    return Math.ceil(specificationStats.value.length / specPageSize)
})

const currentSpecData = computed(() => {
    const start = currentSpecPage.value * specPageSize
    const end = start + specPageSize
    return specificationStats.value.slice(start, end)
})

const totalPages = computed(() => {
    return Math.ceil(manufacturerStats.value.length / pageSize)
})

const currentPageData = computed(() => {
    const start = currentPage.value * pageSize
    const end = start + pageSize
    return manufacturerStats.value.slice(start, end)
})
//低库存计算
const currentLowStockData = computed(() => {
    const start = currentLowStockPage.value * pageSizes
    const end = start + pageSizes
    return lowStockVaccines.value.slice(start, end)
})

const TotalPages = computed(() => {
    return Math.ceil(lowStockVaccines.value.length / pageSizes)
})
const switchLowStockPage = () => {
    currentLowStockPage.value = (currentLowStockPage.value + 1) % TotalPages.value
}
//高库存计算
const currentHighStockData = computed(() => {
    const start = currentHighStockPage.value * HighPageSize
    const end = start + HighPageSize
    return highStockVaccines.value.slice(start, end)
})
const HighTotalPages = computed(() => {
    return Math.ceil(highStockVaccines.value.length / HighPageSize)
})
const switchHighStockPage = () => {
    currentHighStockPage.value = (currentHighStockPage.value + 1) % HighTotalPages.value
}
// 规格分布切换函数
const prevSpecPage = () => {
    if (currentSpecPage.value > 0) {
        currentSpecPage.value--
    }
}

const nextSpecPage = () => {
    if (currentSpecPage.value < specTotalPages.value - 1) {
        currentSpecPage.value++
    }
}

// 生产商分布切换函数
const prevPage = () => {
    if (currentPage.value > 0) {
        currentPage.value--
    }
}

const nextPage = () => {
    if (currentPage.value < totalPages.value - 1) {
        currentPage.value++
    }
}
//低库存切换函数
const LowPrevPage = () => {
    if (currentLowStockPage.value < TotalPages.value > 0) {
        currentLowStockPage.value--
    }
}
const LowNextPage = () => {
    if (currentLowStockPage.value < totalPages.value - 1) {
        currentLowStockPage.value++
    }
}
//高库存切换函数 
const HighPrevPage = () => {
    if (currentHighStockPage.value < HighTotalPages.value > 0) {
        currentHighStockPage.value--
    }
}
const HighNextPage = () => {
    if (currentHighStockPage.value < HighTotalPages.value - 1) {
        currentHighStockPage.value++
    }
}
// 自动轮播
let specAutoPlayTimer = null
let manufacturerAutoPlayTimer = null

const startSpecAutoPlay = () => {
    stopSpecAutoPlay()
    specAutoPlayTimer = setInterval(() => {
        if (currentSpecPage.value < specTotalPages.value - 1) {
            currentSpecPage.value++
        } else {
            currentSpecPage.value = 0 // 回到第一页
        }
    }, 6000) // 6秒切换一次
}

const stopSpecAutoPlay = () => {
    if (specAutoPlayTimer) {
        clearInterval(specAutoPlayTimer)
        specAutoPlayTimer = null
    }
}

const startManufacturerAutoPlay = () => {
    stopManufacturerAutoPlay()
    manufacturerAutoPlayTimer = setInterval(() => {
        if (currentPage.value < totalPages.value - 1) {
            currentPage.value++
        } else {
            currentPage.value = 0 // 回到第一页
        }
    }, 6000) // 6秒切换一次
}

const stopManufacturerAutoPlay = () => {
    if (manufacturerAutoPlayTimer) {
        clearInterval(manufacturerAutoPlayTimer)
        manufacturerAutoPlayTimer = null
    }
}
//低库存自动轮播
let autoPlayTimer = null
const startAutoPlay = () => {
    stopAutoPlay()
    autoPlayTimer = setInterval(() => {
        if (totalPages.value > 1) {
            switchLowStockPage()
        }
    }, 5000) // 5秒自动切换
}
const stopAutoPlay = () => {
    if (autoPlayTimer) {
        clearInterval(autoPlayTimer)
        autoPlayTimer = null
    }
}
//高库存自动轮播 
let HighAutoPlayTimer = null
const HighStartAutoPlay = () => {
    HighStopAutoPlay()
    HighAutoPlayTimer = setInterval(() => {
        if (HighPageSize.value > 1) {
            switchHighStockPage()
        }
    }, 5000) // 5秒自动切换
}
const HighStopAutoPlay = () => {
    if (autoPlayTimer) {
        clearInterval(HighAutoPlayTimer)
        HighAutoPlayTimer = null
    }
}
// 导航函数
const goToVaccineDetail = (vaccineId) => {
    router.push({
        path: '/Vi/VaccineDetail',
        query: { id: vaccineId }
    })
}

// 在组件挂载时开始自动轮播
onMounted(() => {
    fetchVaccineStatistics().then(() => {
        // 规格分布自动轮播
        if (specificationStats.value.length > specPageSize) {
            startSpecAutoPlay()
        }
        // 生产商分布自动轮播
        if (manufacturerStats.value.length > pageSize) {
            startManufacturerAutoPlay()
        }
        //低库存自动轮播
        if (lowStockVaccines.value.length > pageSizes) {
            startAutoPlay()
        }
        //高库存自动轮播
        if (highStockVaccines.value.length > HighPageSize) {
            HighStartAutoPlay()
        }
    })
})


// 鼠标事件处理
const onSpecHover = () => {
    stopSpecAutoPlay()
}

const onSpecLeave = () => {
    if (specificationStats.value.length > specPageSize) {
        startSpecAutoPlay()
    }
}

const onManufacturerHover = () => {
    stopManufacturerAutoPlay()
}

const onManufacturerLeave = () => {
    if (manufacturerStats.value.length > pageSize) {
        startManufacturerAutoPlay()
    }
}
const onLowHover = () => {
    stopAutoPlay()
}
const onLowLeave = () => {
    if (lowStockVaccines.value.length > pageSizes) {
        startAutoPlay()
    }
}
const onHighHover = () => {
    HighStopAutoPlay()
}
const onHighLeave = () => {
    if (highStockVaccines.value.length > pageSizes) {
        HighStartAutoPlay()
    }
}
</script>

<style scoped>
@import "/src/assets/StatisticsVaccine.css";
</style>